<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="用工记录"></page-header>

        <view class="search-box">
            <uni-search-bar
                placeholder="请输入要搜索的内容"
                v-model="searchKey"
                @confirm="handleSearch"
                @input="handleSearch"
                :radius="100"
                cancelButton="none" />
        </view>

        <filter-tabs :activeTab="activeFilter" @tab-change="handleFilterChange" />

        <view class="comm-record-list">
            <record-item
                v-for="(item, index) in filteredStaffList"
                :key="index"
                :item="item"
                @clickItem="editStaff(item)"
                @edit="editStaff(item)"
                @delete="confirmDelete(item)">
                <template #header>
                    <view class="item-header">
                        <view class="header-content" style="display: flex; align-items: center">
                            <image
                                style="margin-right: 10rpx"
                                src="/static/images/caishou.png"
                                class="icon-wrapper"
                                mode="aspectFit"></image>
                            <text class="block-text">{{ item.plotName || '未指定地块' }}</text>
                        </view>
                        <text class="date-text">
                            {{ formatDate(item.startDate) }} ~ {{ formatDate(item.endDate) }}
                        </text>
                    </view>
                </template>

                <template #content>
                    <view class="item-content">
                        <view class="info-row">
                            <view class="info-item" style="width: 50%">
                                <text class="info-label">负责人</text>
                                <text class="info-value">{{ item.personInCharge }}</text>
                            </view>

                            <view class="info-item" style="width: 50%">
                                <text class="info-label">人数</text>
                                <text class="info-value">{{ item.workerCount }}人</text>
                            </view>
                        </view>

                        <view class="info-row">
                            <text class="info-label">用工用途</text>
                            <text class="info-value">{{ item.notes }}</text>
                        </view>
                        <view class="info-row">
                            <text class="info-label">备注</text>
                            <text class="info-value">{{ item.remark }}</text>
                        </view>
                    </view>
                </template>
            </record-item>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="filteredStaffList.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>
        <!-- 无数据提示 -->
        <empty-data v-if="filteredStaffList.length === 0" />
        <view class="add-button" @click="navigateTo('/pages/agriculture/staffManagement/addStaff')">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { staff } from '@/utils/api/index.js'

export default {
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            activeFilter: 'all',
            searchKey: '',
            staffList: [],
            loading: false,
            loadingMore: false,
            hasMore: true,
            pageParams: {
                pageNo: 1,
                pageSize: 30,
            },
        }
    },
    computed: {
        filteredStaffList() {
            return this.staffList
        },
    },
    onShow() {
        this.fetchStaffList()
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.fetchStaffList()
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        // 处理筛选变化
        handleFilterChange(tabValue, filterData) {
            this.activeFilter = tabValue

            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的日期和地块筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.plotId

            // 添加新的筛选条件
            if (filterData) {
                if (filterData.startDate && filterData.endDate) {
                    this.pageParams.startDate = filterData.startDate
                    this.pageParams.endDate = filterData.endDate
                }

                if (filterData.areaId) {
                    this.pageParams.plotId = filterData.areaId
                }
            }

            // 重新请求接口
            this.fetchStaffList()
        },

        // 处理搜索变化
        handleSearch(e) {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 更新关键词搜索参数
            if (this.searchKey) {
                this.pageParams.keyword = this.searchKey
            } else {
                delete this.pageParams.keyword
            }

            // 重新请求接口
            this.fetchStaffList()
        },

        async fetchStaffList(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                const res = await staff.getStaffPage(this.pageParams)

                if (res.code === 0 && res.data) {
                    const newList = res.data.list || []

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.staffList = [...this.staffList, ...newList]
                        // 判断是否还有更多数据
                        this.hasMore = newList.length >= this.pageParams.pageSize
                    } else {
                        // 首次加载或刷新时替换数据
                        this.staffList = newList
                        this.hasMore = newList.length >= this.pageParams.pageSize
                    }
                } else {
                    // 如果API请求失败，使用默认数据
                    if (!isLoadMore) {
                        this.staffList = this.getDefaultData()
                    }
                }
            } catch (error) {
                console.error('获取用工记录失败:', error)
                if (!isLoadMore) {
                    uni.showToast({
                        title: '获取数据失败',
                        icon: 'none',
                    })
                    // 使用默认数据
                    this.staffList = this.getDefaultData()
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        // 获取默认数据，在API请求失败时使用
        getDefaultData() {
            return [
                {
                    id: 1,
                    startDate: '2023-07-23',
                    endDate: '2023-07-23',
                    plotId: '1',
                    plotName: '一号地块',
                    fieldId: '1',
                    workerCount: 5,
                    personInId: 101,
                    personInCharge: '王记得',
                    notes: '果树修剪',
                },
                {
                    id: 2,
                    startDate: '2023-07-23',
                    endDate: '2023-07-23',
                    plotId: '1',
                    plotName: '一号地块',
                    workerCount: 5,
                    personInId: 101,
                    personInCharge: '王记得',
                    notes: '果树施肥',
                },
                {
                    id: 3,
                    startDate: '2023-07-23',
                    endDate: '2023-07-23',
                    plotId: '1',
                    plotName: '一号地块',
                    workerCount: 5,
                    personInId: 101,
                    personInCharge: '王记得',
                    notes: '果树修剪和施肥',
                },
            ]
        },
        navigateTo(url) {
            uni.navigateTo({
                url: url,
            })
        },
        editStaff(item) {
            uni.navigateTo({
                url: `/pages/agriculture/staffManagement/addStaff?id=${item.id}`,
            })
        },
        confirmDelete(item) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除这条用工记录吗？`,
                success: (res) => {
                    if (res.confirm) {
                        this.deleteStaff(item.id)
                    }
                },
            })
        },
        async deleteStaff(id) {
            try {
                uni.showLoading({ title: '删除中...' })

                const res = await staff.deleteStaffRecord(id)

                if (res.code === 0) {
                    // 删除成功，更新列表
                    const index = this.staffList.findIndex((item) => item.id === id)
                    if (index !== -1) {
                        this.staffList.splice(index, 1)
                    }

                    uni.showToast({
                        title: '删除成功',
                        icon: 'success',
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '删除失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('删除用工记录失败:', error)
                uni.showToast({
                    title: '删除失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },
        formatDate(dateString) {
            if (!dateString) return ''
            const date = new Date(dateString)
            const year = date.getFullYear()
            const month = (date.getMonth() + 1).toString().padStart(2, '0')
            const day = date.getDate().toString().padStart(2, '0')

            return `${year}-${month}-${day}`
        },

        // 加载更多数据
        loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            this.fetchStaffList(true)
        },
    },
}
</script>

<style lang="scss"></style>
